﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using EvoGame.Core.Interfaces;

namespace EvoGame.Core.Files
{
	public static partial class FileHandler
	{
		public class Database : File, ILoadable, ISaveable
		{
			protected override FileStream fileStream
			{
				get { return this.file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.Read); }
			}

			protected object data;

			private BinaryFormatter binFormat;

			public Database(string path)
				: base(path)
			{
				this.binFormat = new BinaryFormatter();
			}

			public virtual void Load()
			{
				this.data = this.binFormat.Deserialize(this.fileStream);
			}

			public virtual void Save()
			{
				this.binFormat.Serialize(this.fileStream, this.file);
			}

			public override void Close()
			{
				this.fileStream.Close();
			}

			public bool CheckForUpdates()
			{
				DateTime fileWrite = this.file.LastWriteTimeUtc;
				DateTime dirWrite = this.file.Directory.LastWriteTimeUtc;
				return fileWrite < dirWrite;
			}
		}
	}
}
